import re

import requests
from lxml import etree
from pymongo import MongoClient

from 第三题.chaojiying_Python.chaojiying import Chaojiying_Client

a = requests.get('http://cd.ziroom.com/z/')
r = etree.HTML(a.text)
# # 获取价格图片url
price_img_url = re.search(r'//.*\.png', r.xpath('//div[@class="price "]/span[2]/@style')[0])
print(price_img_url.group(0))
b = requests.get('http:'+price_img_url.group(0))
with open('yzm/yzm.png', 'wb') as f:
    f.write(b.content)

chaojiying = Chaojiying_Client('15276838574', 'foreverlove', '910663')
im = open('yzm/yzm.png', 'rb').read()
ret = chaojiying.PostPic(im, 1010)
# print(ret)
# 验证码
print(ret.get("pic_str"))
price_d = ret.get("pic_str")
price_dict = {}
for i in range(len(price_d)):
    price_dict[str(i)] = int(price_d[i])
print('价格对照字典：' + str(price_dict))
# 连接数据库
client = MongoClient('127.0.0.1', 27017)
collection = client['zrzf']['chengdu']

title = r.xpath('//div[@class="item"]//h5/a/text()')
floor = r.xpath('//div[@class="item"]//div[@class="desc"]/div[1]/text()')
position = r.xpath('//div[@class="item"]//div[@class="desc"]/div[2]/text()')
price_data = r.xpath('//div[@class="item"]//div[@class="price "]')
for i in range(len(title)):
    price_list = [re.search('background-position:(.*)px', i).group(1) for i in price_data[i].xpath('./span/@style')]
    price = []
    for i in range(len(price_list)):
        num = str(int(float(price_list[i]) / 21.4))[1:]
        if num == '':
            num = '0'
        price.append(str(price_dict[num]))
    price = ''.join(price)
    print(price)
    collection.insert_one({
        'title': re.search(r'·(.*)\d', title[i]).group(0)[1:-1],
        "type": re.search(r'\d(.*)-', title[i]).group(0)[:-1],
        "direction": re.search(r'-(.*)', title[i]).group(0)[1:],
        "floor": re.search(r'(\d*)/', floor[i]).group(0)[:-1],
        "all_floor": re.search(r'/(\d*)', floor[i]).group(0)[1:],
        "position": position,
        "price": price
    })
